package service

import (
	"fmt"
	"github.com/kevin186/casbin/lib"
	"github.com/kevin186/casbin/models"
)

func CreateRoleRouter(roleName, routerName, routerMethod string) error {
	roles := &models.Role{}
	router := []*models.Router{}
	if err := lib.DB.Where("r_name = ? and r_method = ?", routerName, routerMethod).Find(&router).Error; err != nil {
		fmt.Println("增加CreateRoleRouter失败", err.Error())
		return err
	}
	//lib.DB.Preload("Routers").Find(&role)
	lib.DB.Where("role_name = ?", roleName).Find(&roles)
	fmt.Println(roles)
	if err := lib.DB.Model(&roles).Association("Routers").Append(router); err != nil {
		fmt.Println("[deleteRole]: 删除Role失败", err.Error())
		return err
	}
	fmt.Println("------------"+roleName, routerName, routerMethod)
	_, err := lib.E.AddPolicy(roleName, "/"+routerName, routerMethod)
	if err != nil {
		fmt.Println("创建createRoleRouter成功后增加addpolicy失败")
	}
	fmt.Println("创建createRoleRouter成功后增加addpolicy成功")

	return nil
}
